package com.wanmait.wanmarecruit.interceptor;

import com.auth0.jwt.exceptions.JWTVerificationException;
import com.wanmait.wanmarecruit.entity.Manager;
import com.wanmait.wanmarecruit.service.ManagerService;
import com.wanmait.wanmarecruit.util.JWTUtils;
import com.wanmait.wanmarecruit.util.SystemContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class ManageLoginInterceptor implements HandlerInterceptor {
    @Resource
    private ManagerService managerService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        if ("OPTIONS".equals(method))
        {
            return true;
        }
        String token = request.getHeader("token");
        if (token==null)
        {
            throw new JWTVerificationException("没有携带令牌token");
        }
//        Integer id = Integer.parseInt(JWTUtils.getAudience(token));
//        Manager manager = managerService.getById(id);
//        if (manager==null)
//        {
//            throw new JWTVerificationException("没有找到管理员，认证失败");
//        }
        Manager manager = (Manager)redisTemplate.opsForValue().get(token);
        if (manager==null)
        {
            throw new JWTVerificationException("没有找到管理员，认证失败");
        }
        JWTUtils.verifyToken(token,manager.getPass());
        request.setAttribute("loginManager",manager);
        return true;
    }
}
